package com.ade.warehouse.page;

import com.ade.warehouse.pojo.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import util.CookieUtils;
import util.JsonUtils;
import util.MockRedis;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.regex.Pattern;

/**
 * @Author: zhy
 * @email: 1269679946@qq.com
 * @Date: 2019/1/22
 * @DESC： 权限过滤
 */

@WebFilter(filterName = "adminOptionFilter")
public class AdminFilter implements Filter {


    private MockRedis jedisClient;


    private HashSet<String> exclusions = new HashSet<>();


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext servletContext = filterConfig.getServletContext();
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        jedisClient = (MockRedis) ctx.getBean("loginMockRedis");

        String param = filterConfig.getInitParameter("exclusions");
        if (StringUtils.isNotBlank(param)) {
            String[] exclusionurl = param.split(",");
            for (String url : exclusionurl) {
                exclusions.add(url);
            }
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //获取cookie
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String token = CookieUtils.getCookieValue(httpServletRequest, "token", false);



        // 定义表示变量 并验证用户请求URI 是否包含不过滤路径
        String uri=httpServletRequest.getRequestURI();
        if (exclusions.contains(uri)||
                Pattern.matches("\\/static\\/(([a-zA-Z0-9_-]+)+\\/)?(.*)",uri)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //获取用户数据
        String user = jedisClient.get("SESSION:" + token);
        if (StringUtils.isBlank(user)) {
            //用户登录已过期
            httpServletResponse.sendRedirect("/views/direction.html");
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

    }

    @Override
    public void destroy() {
    }


}